package cn.itcast.bos.service.base.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import cn.itcast.bos.dao.CourierDao;
import cn.itcast.bos.dao.TakeTimeDao;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.TakeTime;
import cn.itcast.bos.service.base.CourierSerivce;
import cn.itcast.bos.service.base.TakeTimeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.FixedAreaDao;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.FixedAreaService;

@Transactional
@Service
public class FixedAreaServiceImpl implements FixedAreaService {
	@Autowired
	private FixedAreaDao fixedAreaDao;

	@Override

	public void saveOrUpdate(FixedArea model) {
		fixedAreaDao.save(model);
	}

	@Override
	public Page<FixedArea> pageQuery(Pageable pageable, FixedArea fixedArea) {
		Specification<FixedArea> spe = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList();
				if (StringUtils.isNotBlank(fixedArea.getId())) {
					Predicate p1 = cb.equal(root.get("id").as(String.class), fixedArea.getId());
					predicates.add(p1);
				}
				// 对所属单位进行模糊查询
				if (StringUtils.isNotBlank(fixedArea.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class),
							"%" + fixedArea.getCompany().trim() + "%");
					predicates.add(p2);
				}

				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		};

		return fixedAreaDao.findAll(spe, pageable);
	}

	public void deleteFixedAreaById(String ids) {
		if (StringUtils.isNotBlank(ids)) {
			String[] arr = ids.split(",");
			for (String id : arr) {
				fixedAreaDao.delete(id);
			}
		}
	}
	//定区关联courier
	@Autowired
	private TakeTimeDao takeTimeDao;
	@Autowired
	private CourierDao courierDao;


    @Override
    public void associationCourierToFixedArea(FixedArea model, Integer takeTimeId, Integer courierId) {
        //获取定区
		FixedArea fixedAreaTemple= fixedAreaDao.findOne(model.getId());
		Courier courier = courierDao.findOne(courierId);
		//获取taketime
		TakeTime takeTime = takeTimeDao.findOne(takeTimeId);
		courier.setTakeTime(takeTime);
		fixedAreaTemple.getCouriers().add(courier);
	}

}
